package com.shiku.imserver.repository;

import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.shiku.imserver.CoreService;
import com.shiku.imserver.common.IService;
import com.shiku.imserver.common.ImConfig;
import com.shiku.imserver.common.constant.KConstants;
import com.shiku.imserver.common.message.ChatMessage;
import com.shiku.imserver.common.message.PullBatchGroupMessage;
import com.shiku.imserver.common.message.PullBatchGroupRespMessage;
import com.shiku.imserver.common.packets.ImPacket;
import com.shiku.imserver.common.proto.MessageProBuf;
import com.shiku.imserver.common.utils.ProBufUtils;
import com.shiku.imserver.service.IMBeanUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

public class MessageRepositoryOld extends BaseRepository implements IService {
    private static final String LASTCHAT_DB = "shiku_lastChats";
    private static final String LASTCHAT_MUC_COLLECTION = "lastChats_muc";
    private static final String MESSAGE_OFFLINE = "message_offline";
    private static final String MSGS_DB = "shiku_msgs";
    private static final String MUCMsg_ = "mucmsg_";
    private static Logger logger = LoggerFactory.getLogger(MessageRepositoryOld.class);
    private MongoDatabase chatMsgDB;
    private MongoDatabase lastMsgDB;
    private MongoDatabase mucdb;
    private MongoDatabase offMsgDB;
    Queue<ChatMessage> queue = new LinkedBlockingQueue();
    MessageRepositoryThread thread;

    public boolean initialize() {
        ImConfig.MongoConfig mongoConfig = IMBeanUtils.getImconfig().getMongoConfig();
        MongoClient mongoClient = IMBeanUtils.getBeanManager().getMongoClient();
        try {
            MongoClientURI uri = new MongoClientURI(mongoConfig.getUri());
            if (uri.getUsername() != null) {
                MongoCredential chatMsg_Credentials = MongoCredential.createCredential(uri.getUsername(), MSGS_DB, uri.getPassword());
                MongoCredential lastMsg_Credentials = MongoCredential.createCredential(uri.getUsername(), "shiku_lastChats", uri.getPassword());
                mongoClient.getCredentialsList().add(chatMsg_Credentials);
                mongoClient.getCredentialsList().add(lastMsg_Credentials);
            }
            this.chatMsgDB = mongoClient.getDatabase(MSGS_DB);
            this.lastMsgDB = mongoClient.getDatabase("shiku_lastChats");
            if (uri.getUsername() != null) {
                mongoClient.getCredentialsList().add(MongoCredential.createCredential(uri.getURI(), "imRoom", uri.getPassword()));
            }
            this.mucdb = mongoClient.getDatabase("imRoom");
            MongoCollection<Document> msgsCollection = this.chatMsgDB.getCollection(MSGS_DB);
            msgsCollection.createIndex(new BasicDBObject("sender", 1));
            msgsCollection.createIndex(new BasicDBObject("receiver", 1));
            msgsCollection.createIndex(new BasicDBObject("sender", 1).append("receiver", 1));
            msgsCollection.createIndex(new BasicDBObject("sender", 1).append("receiver", 1).append("ts", 1));
            this.lastMsgDB.getCollection("shiku_lastChats").createIndex(new BasicDBObject("timeSend", 1));
            this.offMsgDB = mongoClient.getDatabase(MESSAGE_OFFLINE);
            this.thread = new MessageRepositoryThread();
            this.thread.start();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void archiveMessage(ChatMessage model) {
        if (1 == model.getMessageHead().getChatType()) {
            storeChatMessage(model);
        } else if (2 == model.getMessageHead().getChatType()) {
            storeGroupMessage(model);
        }
    }

    /* access modifiers changed from: private */
    public void storeChatMessage(ChatMessage model) {
        if (model.getType() != 0) {
            if (26 == model.getType()) {
                IMBeanUtils.getMessageRepository().updateMsgReadStatus(Long.valueOf(model.getFromUserId()).longValue(), model.getContent());
            } else if (5 == model.getType() / 100) {
                String from = model.getMessageHead().getFrom();
                String to = model.getMessageHead().getTo();
                IMBeanUtils.getBeanManager().getNewFirendRepository().saveNewFirendRecord(CoreService.parseBareUserId(from), CoreService.parseBareUserId(to), from, model.getType(), model.getContent());
            } else if (9 == model.getType() / 100) {
            } else {
                if (120 >= model.getType() || 202 == model.getType()) {
                    Document dbObj = new Document();
                    dbObj.put("message", model.toString());
                    dbObj.put("direction", 0);
                    dbObj.put("sender", model.getFromUserId());
                    dbObj.put("receiver", model.getToUserId());
                    if (model.getFromUserId().equals(model.getToUserId())) {
                        dbObj.put("sender", model.getMessageHead().getFrom());
                        dbObj.put("receiver", model.getMessageHead().getTo());
                    }
                    dbObj.put("sender_jid", model.getMessageHead().getFrom());
                    dbObj.put("receiver_jid", model.getMessageHead().getTo());
                    dbObj.put("ts", Long.valueOf(System.currentTimeMillis()));
                    dbObj.put("contentType", Short.valueOf(model.getType()));
                    dbObj.put("messageId", model.getMessageHead().getMessageId());
                    dbObj.put("timeSend", Long.valueOf(model.getTimeSend()));
                    dbObj.put("deleteTime", Long.valueOf(model.getDeleteTime()));
                    dbObj.put("isRead", 0);
                    dbObj.put("isEncrypt", Boolean.valueOf(model.isEncrypt()));
                    if (model.getContent() != null) {
                        dbObj.put("content", model.getContent());
                    }
                    getCollection(this.chatMsgDB, Long.valueOf(model.getFromUserId()).longValue()).insertOne(dbObj);
                    dbObj.replace("direction", 1);
                    dbObj.replace("sender", model.getToUserId());
                    dbObj.replace("receiver", model.getFromUserId());
                    if (model.getFromUserId().equals(model.getToUserId())) {
                        dbObj.put("sender", model.getMessageHead().getTo());
                        dbObj.put("receiver", model.getMessageHead().getFrom());
                    }
                    dbObj.remove("_id");
                    getCollection(this.chatMsgDB, Long.valueOf(model.getToUserId()).longValue()).insertOne(dbObj);
                    LastChatModel lastChat = new LastChatModel();
                    lastChat.setMessageId(model.getMessageHead().getMessageId());
                    lastChat.setContent(model.getContent());
                    lastChat.setUserId(model.getFromUserId());
                    lastChat.setJid(model.getToUserId());
                    lastChat.setIsRoom(0);
                    lastChat.setType(model.getType());
                    lastChat.setTimeSend(model.getTimeSend());
                    lastChat.setEncrypt(model.isEncrypt());
                    lastChat.setFrom(model.getMessageHead().getFrom());
                    lastChat.setTo(model.getMessageHead().getTo());
                    lastChat.setFromUserName(model.getFromUserName());
                    lastChat.setToUserName(model.getToUserName());
                    refreshLastChat(lastChat);
                }
            }
        }
    }

    /* access modifiers changed from: private */
    public void storeGroupMessage(ChatMessage model) {
        try {
            if (model.getType() != 0 && 26 != model.getType()) {
                String roomJid = model.getMessageHead().getTo();
                Document dbObj = new Document();
                dbObj.put("message", model.toString());
                dbObj.put("room_jid", roomJid);
                dbObj.put("sender_jid", model.getMessageHead().getFrom());
                dbObj.put("sender", model.getFromUserId());
                dbObj.put("ts", Long.valueOf(System.currentTimeMillis()));
                dbObj.put("contentType", Short.valueOf(model.getType()));
                dbObj.put("messageId", model.getMessageHead().getMessageId());
                dbObj.put("timeSend", Long.valueOf(model.getTimeSend()));
                dbObj.put("deleteTime", Long.valueOf(model.getDeleteTime()));
                if (model.getContent() != null) {
                    dbObj.put("content", model.getContent());
                }
                this.mucdb.getCollection(MUCMsg_ + roomJid).insertOne(dbObj);
                LastChatModel lastChat = new LastChatModel();
                lastChat.setMessageId(model.getMessageHead().getMessageId());
                lastChat.setContent(model.getContent());
                lastChat.setUserId(model.getFromUserId());
                lastChat.setJid(roomJid);
                lastChat.setIsRoom(1);
                lastChat.setType(model.getType());
                lastChat.setTimeSend(model.getTimeSend());
                lastChat.setEncrypt(model.isEncrypt());
                lastChat.setFrom(model.getMessageHead().getFrom());
                lastChat.setTo(model.getMessageHead().getTo());
                lastChat.setFromUserName(model.getFromUserName());
                lastChat.setToUserName(model.getToUserName());
                refreshLastChat(lastChat);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ChatMessage loadGroupMessage(String roomJid, String messageId) {
        Document document = (Document) this.mucdb.getCollection(MUCMsg_ + roomJid).find(new Document("messageId", messageId)).first();
        if (document == null) {
            return null;
        }
        return (ChatMessage) JSON.parseObject(document.getString("message"), ChatMessage.class);
    }

    public long loadGroupHistoryCount(String jid, long lastTime) {
        MongoCollection<Document> collection = this.mucdb.getCollection(MUCMsg_ + jid);
        Document query = new Document("room_jid", jid);
        query.append("timeSend", new Document("$gt", Long.valueOf(lastTime)));
        return collection.count(query);
    }

    public void pullBatchGroupHistoryMessage(ChannelContext channelContext, PullBatchGroupMessage pullBatchGroupMessageReq) {
        PullBatchGroupRespMessage groupHistoryMessage;
        if (pullBatchGroupMessageReq.getJidList() != null) {
            long endTime = pullBatchGroupMessageReq.getEndTime();
            String from = pullBatchGroupMessageReq.getMessageHead().getFrom();
            try {
                for (String str : pullBatchGroupMessageReq.getJidList()) {
                    if (channelContext.isClosed) {
                        logger.error(" channelContext isClosed => {} " + from);
                        return;
                    }
                    if (KConstants.isDebug) {
                        logger.info("pull message userId > {}  jid {}", from, str);
                    }
                    String[] split = str.split(",");
                    if (2 <= split.length && (groupHistoryMessage = queryGroupHistoryMessage(split[0], Long.valueOf(split[1]).longValue(), endTime)) != null) {
                        groupHistoryMessage.setMessageId(pullBatchGroupMessageReq.getMessageHead().getMessageId());
                        ImPacket imPacket = ProBufUtils.encodeImPacket(groupHistoryMessage, MessageProBuf.PullGroupMessageRespProBuf.getDescriptor());
                        imPacket.setCommand((short)15);
                        CoreService.send(channelContext, imPacket);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }

    public List<ChatMessage> loadGroupHistoryMessage(String jid, long seconds) {
        List<ChatMessage> result = new ArrayList<>();
        Document query = new Document("room_jid", jid);
        query.append("timeSend", new Document("$gt", Long.valueOf(System.currentTimeMillis() - seconds)));
        MongoCursor<Document> iterator = this.mucdb.getCollection(MUCMsg_ + jid).find(query).sort(new Document("timeSend", -1)).limit(100).iterator();
        while (iterator.hasNext()) {
            try {
                ChatMessage message = (ChatMessage) JSON.parseObject(((Document) iterator.next()).getString("message"), ChatMessage.class);
                if (message != null) {
                    result.add(message);
                }
            } catch (Exception e) {
                logger.error(" Exception {}", e.getMessage());
            } catch (Throwable th) {
                if (iterator != null) {
                    iterator.close();
                }
                throw th;
            }
        }
        if (iterator != null) {
            iterator.close();
        }
        Collections.reverse(result);
        return result;
    }

    public PullBatchGroupRespMessage queryGroupHistoryMessage(String jid, long startTime, long endTime) {
        int limit = 20;
        Document query = new Document("room_jid", jid);
        query.append("timeSend", new Document("$gt", Long.valueOf(startTime)).append("$lt", Long.valueOf(endTime)));
        MongoCollection<Document> collection = this.mucdb.getCollection(MUCMsg_ + jid);
        long count = collection.count(query);
        if (0 == count) {
            return null;
        }
        if (count < ((long) 20)) {
            limit = (int) count;
        }
        MongoCursor<Document> iterator = collection.find(query).sort(new Document("timeSend", -1)).limit(limit).iterator();
        List<ChatMessage> messageList = new ArrayList<>();
        while (iterator.hasNext()) {
            try {
                ChatMessage message = (ChatMessage) JSON.parseObject(((Document) iterator.next()).getString("message"), ChatMessage.class);
                if (message != null) {
                    messageList.add(message);
                }
            } catch (Exception e) {
                logger.error(" Exception {}", e.getMessage());
            } catch (Throwable th) {
                if (iterator != null) {
                    iterator.close();
                }
                throw th;
            }
        }
        if (iterator != null) {
            iterator.close();
        }
        Collections.reverse(messageList);
        PullBatchGroupRespMessage result = new PullBatchGroupRespMessage();
        result.setJid(jid);
        result.setCount(count);
        result.setMessageList(messageList);
        return result;
    }

    public List<ChatMessage> pullGroupHistoryMessage(String jid, int size, long startTime, long endTime) {
        List<ChatMessage> result = new ArrayList<>();
        Document query = new Document("room_jid", jid);
        MongoCollection<Document> collection = this.mucdb.getCollection(MUCMsg_ + jid);
        if (0 < startTime) {
            query.append("timeSend", new Document("$gt", Long.valueOf(startTime)));
        }
        if (0 < endTime) {
            query.append("timeSend", new Document("$lt", Long.valueOf(endTime)));
        }
        MongoCursor<Document> iterator = collection.find(query).sort(new Document("timeSend", -1)).limit(size).iterator();
        while (iterator.hasNext()) {
            try {
                ChatMessage message = (ChatMessage) JSON.parseObject(((Document) iterator.next()).getString("message"), ChatMessage.class);
                if (message != null) {
                    result.add(message);
                }
            } catch (Exception e) {
                logger.error(" Exception {}", e.getMessage());
            } catch (Throwable th) {
                if (iterator != null) {
                    iterator.close();
                }
                throw th;
            }
        }
        if (iterator != null) {
            iterator.close();
        }
        Collections.reverse(result);
        return result;
    }

    public void refreshLastChat(LastChatModel model) {
        MongoCollection<Document> collection;
        if (model.getJid() != null) {
            if (model.getIsRoom() == 0) {
                collection = getCollection(this.lastMsgDB, Long.valueOf(model.getUserId()).longValue());
            } else {
                collection = this.lastMsgDB.getCollection(LASTCHAT_MUC_COLLECTION);
            }
            collection.find().first();
            Document query = new Document("jid", model.getJid());
            Document values = new Document("type", Integer.valueOf(model.getType()));
            values.append("messageId", model.getMessageId());
            values.append("timeSend", Long.valueOf(model.getTimeSend()));
            values.append("content", model.getContent());
            values.append("userId", model.getUserId());
            values.append("jid", model.getJid());
            values.append("isRoom", Integer.valueOf(model.getIsRoom()));
            values.append("isEncrypt", Boolean.valueOf(model.isEncrypt()));
            values.append("from", model.getFrom());
            values.append("to", model.getTo());
            values.append("fromUserName", model.getFromUserName());
            values.append("toUserName", model.getToUserName());
            if (1 != model.getIsRoom()) {
                query.append("userId", model.getUserId());
            }
            if (0 < collection.count(query)) {
                collection.updateMany(query, new Document("$set", values));
            } else {
                collection.insertOne(values);
            }
            if (1 != model.getIsRoom() && !model.getUserId().equals(model.getJid())) {
                if (1 != model.getIsRoom()) {
                    query.replace("userId", model.getJid());
                    query.replace("jid", model.getUserId());
                    values.replace("userId", model.getJid());
                    values.replace("jid", model.getUserId());
                }
                values.remove("_id");
                MongoCollection<Document> collection2 = getCollection(this.lastMsgDB, Long.valueOf(model.getJid()).longValue());
                if (0 < collection2.count(query)) {
                    collection2.updateMany(query, new Document("$set", values));
                } else {
                    collection2.insertOne(values);
                }
            }
        }
    }

    public void updateMsgReadStatus(long sender, String msgId) {
        if (msgId != null) {
            getCollection(this.chatMsgDB, sender).updateOne(new Document("messageId", msgId), new Document("$set", new BasicDBObject("isRead", 1)));
        }
    }

    public void deleteChatOffToJID(String userJid) {
    }

    public ChatMessage loadChatMessage(String userId, String messageId) {
        Document document = (Document) getCollection(this.chatMsgDB, (long) Integer.valueOf(userId).intValue()).find(new Document("messageId", messageId)).first();
        if (document == null) {
            return null;
        }
        return (ChatMessage) JSON.parseObject(document.getString("message"), ChatMessage.class);
    }

    public List<ChatMessage> pullChatHistoryMessage(String userJid, String toJid, int size, long startTime, long endTime) {
        List<ChatMessage> result = new ArrayList<>();
        Document query = new Document("sender", userJid);
        query.append("receiver", toJid);
        if (0 < startTime) {
            query.append("timeSend", new Document("$gt", Long.valueOf(startTime)));
        }
        if (0 < endTime) {
            query.append("timeSend", new Document("$lt", Long.valueOf(endTime)));
        }
        MongoCursor<Document> iterator = getCollection(this.chatMsgDB, (long) Integer.valueOf(userJid).intValue()).find(query).sort(new Document("timeSend", -1)).limit(size).iterator();
        while (iterator.hasNext()) {
            try {
                ChatMessage message = (ChatMessage) JSON.parseObject(((Document) iterator.next()).getString("message"), ChatMessage.class);
                if (message != null) {
                    result.add(message);
                }
            } catch (Exception e) {
                logger.error(" Exception {}", e.getMessage());
            }
        }
        Collections.reverse(result);
        return result;
    }

    public Queue<ChatMessage> loadChatOffToJID(String userJid, boolean delete) {
        Queue<ChatMessage> result = new LinkedList<>();
        Document query = new Document("receiver", userJid);
        Document sort = new Document("timeSend", 1);
        MongoCollection<Document> collection = getCollection(this.offMsgDB, (long) Integer.valueOf(userJid).intValue());
        MongoCursor<Document> iterator = collection.find(query).sort(sort).iterator();
        while (iterator.hasNext()) {
            try {
                ChatMessage message = (ChatMessage) JSON.parseObject(((Document) iterator.next()).getString("message"), ChatMessage.class);
                if (message != null) {
                    result.add(message);
                }
            } catch (Exception e) {
                logger.error(" Exception {}", e.getMessage());
            } catch (Throwable th) {
                if (iterator != null) {
                    iterator.close();
                }
                throw th;
            }
        }
        if (iterator != null) {
            iterator.close();
        }
        collection.deleteMany(query);
        return result;
    }

    public void storeChatOffMessage(ChatMessage message) {
        try {
            Document dbObj = new Document();
            dbObj.put("message", message.toString());
            dbObj.put("to", message.getMessageHead().getTo());
            dbObj.put("from", message.getMessageHead().getFrom());
            dbObj.put("sender", message.getFromUserId());
            dbObj.put("receiver", message.getToUserId());
            dbObj.put("contentType", Short.valueOf(message.getType()));
            dbObj.put("messageId", message.getMessageHead().getMessageId());
            dbObj.put("timeSend", Long.valueOf(message.getTimeSend()));
            dbObj.put("content", message.getContent());
            getCollection(this.offMsgDB, (long) Integer.valueOf(message.getToUserId()).intValue()).insertOne(dbObj);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public boolean offerMessage(ChatMessage message) {
        return this.queue.offer(message);
    }

    public class MessageRepositoryThread extends Thread {
        public MessageRepositoryThread() {
        }

        public void run() {
            while (true) {
                if (MessageRepositoryOld.this.queue.isEmpty()) {
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ChatMessage message = MessageRepositoryOld.this.queue.poll();
                    if (1 == message.getMessageHead().getChatType()) {
                        MessageRepositoryOld.this.storeChatMessage(message);
                    } else if (2 == message.getMessageHead().getChatType()) {
                        MessageRepositoryOld.this.storeGroupMessage(message);
                    }
                }
            }
        }
    }
}
